package com.aidong.util;

/**
 * Created by john on 16-11-2.
 */
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class ExportXls {
    protected HttpServletResponse response;
    protected OutputStream outputStream;
    protected WritableWorkbook workBook;
    protected WritableSheet sheet;
    protected int rowNum;

    public ExportXls(String fileName, String sheetName) throws Exception {
        this.outputStream = new FileOutputStream(fileName);
        this.workBook = Workbook.createWorkbook(this.outputStream);
        this.sheet = this.workBook.createSheet(sheetName, 0);
        this.rowNum = 0;
    }

    public ExportXls(HttpServletResponse response, String fileName, String sheetName) throws Exception {
        this.response = response;
        String fn = new String(fileName.getBytes(), "iso-8859-1");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + fn + ".xls");
        this.outputStream = response.getOutputStream();
        this.workBook = Workbook.createWorkbook(this.outputStream);
        this.sheet = this.workBook.createSheet(sheetName, 0);
        this.rowNum = 0;
    }

    public WritableSheet getSheet() {
        return this.sheet;
    }

    public WritableSheet addSheet(String sheetName) {
        this.sheet = this.workBook.createSheet(sheetName, this.workBook.getNumberOfSheets());
        this.rowNum = 0;
        return this.sheet;
    }

    public void setWidth(int... wid) {
        for(int i = 0; i < wid.length; ++i) {
            this.sheet.setColumnView(i, wid[i]);
        }

    }

    public int addHead(String... name) throws Exception {
        for(int i = 0; i < name.length; ++i) {
            this.sheet.addCell(new Label(i, this.rowNum, name[i]));
        }

        ++this.rowNum;
        return this.rowNum;
    }

    public int addRow(Object... value) throws Exception {
        if(this.rowNum > '\ufffa') {
            return -1;
        } else {
            for(int i = 0; i < value.length; ++i) {
                if(value[i] != null) {
                    if(value[i] instanceof Number) {
                        this.sheet.addCell(new jxl.write.Number(i, this.rowNum, ((Number)value[i]).doubleValue()));
                    } else {
                        this.sheet.addCell(new Label(i, this.rowNum, value[i].toString()));
                    }
                }
            }

            ++this.rowNum;
            return this.rowNum;
        }
    }

    public void close() throws Exception {
        this.workBook.write();
        this.workBook.close();
        this.outputStream.flush();
        this.outputStream.close();
    }
}
